package com.wechat.scheme.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.servlet.http.HttpServletRequest;

public class PageRequestUtil {

    private static final String PARAM_NAME_PAGE_NUM = "p";
    public static final String PARAM_NAME_PAGE_SIZE = "ps";
    public static final int DEFAULT_LIMIT = 10;
    public static final String PARAM_NAME_ORDERBY = "orderby";
    public static final String PARAM_NAME_DIRECTION = "direction";
    public static final String PARAM_DEFAULT_ORDER = "modified";
    public static final String PARAM_DEFAULT_CREATE_ORDER = "created";
    //默认下载分页参数
    public static final Pageable DEFAULT_EXPORT_PAGEABLE = PageRequest.of(0,10000,Sort.by(Sort.Direction.ASC,PARAM_DEFAULT_CREATE_ORDER));

    public static PageRequest getPageRequest(HttpServletRequest request, String defaultOrderBy) {
        int pageNum = str2Int(request.getParameter(PARAM_NAME_PAGE_NUM) , 1);
        int pageSize = str2Int(request.getParameter(PARAM_NAME_PAGE_SIZE), DEFAULT_LIMIT);
        String orderBy = request.getParameter(PARAM_NAME_ORDERBY);
        if (StringUtils.isBlank(orderBy)) {
            orderBy = defaultOrderBy;
        }
        String direction = request.getParameter(PARAM_NAME_DIRECTION);
        Sort.Direction d = Sort.Direction.DESC;
        if ("ASC".equalsIgnoreCase(direction)) {
            d = Sort.Direction.ASC;
        }
        Sort sort = Sort.by(d,orderBy);
        PageRequest pageRequest =PageRequest.of(pageNum -1 ,pageSize,sort);
        return pageRequest;
    }

    public static int str2Int(String str, int nullVal) {
        int result = nullVal;
        try {
            if(str != null && StringUtils.isNumeric(str)){
                result = Integer.parseInt(str);
            }
        } catch (Exception e) {

        }
        return result;
    }
}
